package com.gufe.service.admin.impl.club;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gufe.entity.PPTQueryParam;
import com.gufe.entity.PrecollectMember;
import com.gufe.exception.NullDataException;
import com.gufe.mapper.admin.club.RetireMemberMapper;
import com.gufe.result.PageResult;
import com.gufe.service.admin.club.RetireMemberService;
import com.gufe.vo.PPTvo.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RetireRetireMemberServiceImpl implements RetireMemberService {

    @Autowired
    private RetireMemberMapper retireMemberMapper;

    /**
     * 获取预征班展示数据
     *
     * @return
     */
    public PageResult<MemberVO> getMembers(PPTQueryParam pptQueryParam) {
        // 将前端传递过来的 男 和 女 转换为其对应的数字 男：1 女：0
        if (Objects.equals(pptQueryParam.getGender(), "男")) {
            pptQueryParam.setGender("1");
        } else if (Objects.equals(pptQueryParam.getGender(), "女")) {
            pptQueryParam.setGender("0");
        }

        List<Integer> statusList = null;
        String status = pptQueryParam.getStatus();
        if (status != null && !Objects.equals(status, "")) {
            // 将字符串转换为 List<Integer>
            statusList = Arrays.stream(status.split(",")) // 按逗号分割成字符串数组
                    .map(Integer::parseInt) // 将每个字符串转换为整数
                    .collect(Collectors.toList()); // 收集为 List

        }
        // 设置分页参数
        PageHelper.startPage(pptQueryParam.getPage(), pptQueryParam.getPageSize());

        // 执行查询
        List<MemberVO> memberVOList = retireMemberMapper.getMembers(pptQueryParam, statusList);

        // 解析查询结果并封装
        Page<MemberVO> p = (Page<MemberVO>) memberVOList;

        return new PageResult<>(p.getTotal(), p.getResult());
    }


    /**
     * 根据ID获取预征班成员信息
     *
     * @param id
     * @return
     */
    public PrecollectMember getMemberById(Integer id) {
        PrecollectMember member = retireMemberMapper.getMemberById(id);
        return member;
    }

    /**
     * 根据ID导出预征班成员信息
     *
     * @param id
     */
    public XSSFWorkbook exportInfo(Integer id) throws IOException {
        if (id == null) {
            throw new NullDataException();
        }

        // 读取 Excel 模版
        InputStream templateStream = getClass().getClassLoader().getResourceAsStream("module/贵州财经大学预征班学员申请表Demo.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(templateStream);
        Sheet sheet = workbook.getSheetAt(0); // 选择第一个工作表


        // 获取成员数据
        PrecollectMember member = getMemberById(id);

        // 插入照片
        if (member.getImgUrl() != null && !member.getImgUrl().isEmpty()) {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                // 创建 HTTP 请求
                HttpGet httpGet = new HttpGet(member.getImgUrl());

                // 执行请求并获取响应
                try (CloseableHttpResponse response = httpClient.execute(httpGet);
                     InputStream inputStream = response.getEntity().getContent()) {

                    // 将图片流读取为字节数组
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                    byte[] data = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                        buffer.write(data, 0, bytesRead);
                    }
                    byte[] imageBytes = buffer.toByteArray();

                    // 判断图片类型
                    int pictureType = Workbook.PICTURE_TYPE_JPEG;
                    if (member.getImgUrl().toLowerCase().endsWith(".png")) {
                        pictureType = Workbook.PICTURE_TYPE_PNG;
                    }

                    // 将图片添加到工作簿
                    int pictureIdx = workbook.addPicture(imageBytes, pictureType);

                    // 创建绘图工具
                    CreationHelper helper = workbook.getCreationHelper();
                    Drawing<?> drawing = sheet.createDrawingPatriarch();

                    // 设置图片位置（示例：Excel中的G3单元格）
                    ClientAnchor anchor = helper.createClientAnchor();
                    anchor.setCol1(6);  // 第7列（G列）
                    anchor.setRow1(3);  // 第4行

                    // 插入图片并调整大小
                    Picture pict = drawing.createPicture(anchor, pictureIdx);
                    // 获取图片原始尺寸（单位：像素）
                    double imageWidth = pict.getImageDimension().getWidth();
                    double imageHeight = pict.getImageDimension().getHeight();

                    // 计算单元格总宽高（像素）
                    float cellWidth = sheet.getColumnWidthInPixels(6); // G列宽（像素）
                    float cellHeight = 0;
                    for (int i = 3; i <= 6; i++) {
                        Row row = sheet.getRow(i);
                        if (row == null) continue;
                        cellHeight += row.getHeightInPoints() * 96 / 72; // 行高转像素
                    }
                    // 计算缩放比例
                    double scale = Math.min(cellWidth / imageWidth, cellHeight / imageHeight);


                    // 计算最终显示尺寸
                    double displayWidth = imageWidth * scale;
                    double displayHeight = imageHeight * scale;

                    // 计算居中偏移（EMU单位）
                    long dx = (long) ((cellWidth - displayWidth) / 2 * 9525);
                    long dy = (long) ((cellHeight - displayHeight) / 2 * 9525);

                    // 添加参数有效性检查
                    if (dx < 0 || dy < 0) {
                        throw new IllegalArgumentException("计算得到负偏移量，检查单元格尺寸是否过小");
                    }

                    // 设置锚点参数
                    anchor.setDx1((int) dx);
                    anchor.setDy1((int) dy);

                    // 调整图片大小
                    pict.resize(scale);


                }
            } catch (IOException e) {
                throw new IOException("图片下载或插入失败: " + e.getMessage());
            }
        }


        // 填充 Excel 数据
        sheet.getRow(2).getCell(1).setCellValue(getSafeString(member.getCollege()));
        sheet.getRow(2).getCell(5).setCellValue(
                member.getFormTime() != null ?
                        member.getFormTime().substring(0, 10) : "-"
        );

        // 第 3 行
        sheet.getRow(3).getCell(1).setCellValue(getSafeString(member.getName()));
        sheet.getRow(3).getCell(3).setCellValue(
                Objects.equals(member.getGender(), "1") ? "男" : "女"
        );
        sheet.getRow(3).getCell(5).setCellValue(getSafeString(member.getBirthDate().toString()));

        // 第 4 行
        sheet.getRow(4).getCell(1).setCellValue(getSafeString(member.getNationality()));
        sheet.getRow(4).getCell(3).setCellValue(getSafeString(member.getNativePlace()));
        sheet.getRow(4).getCell(5).setCellValue(getSafeString(member.getPoliticalAffiliation()));

        // 第 5 行
        sheet.getRow(5).getCell(1).setCellValue(getSafeString(member.getCollege()));
        sheet.getRow(5).getCell(4).setCellValue(getSafeString(member.getClassName()));

        // 第 6 行
        sheet.getRow(6).getCell(1).setCellValue(getSafeString(member.getStudentId()));
        sheet.getRow(6).getCell(4).setCellValue(getSafeString(member.getIdCard()));

        // 第 7 行
        sheet.getRow(7).getCell(1).setCellValue(getSafeString(member.getContactNumber()));
        sheet.getRow(7).getCell(4).setCellValue(getSafeString(member.getHomeAddress()));

        // 第 8 行
        sheet.getRow(8).getCell(1).setCellValue(getSafeString(member.getResume()));

        // 第 9 行
        sheet.getRow(9).getCell(1).setCellValue(getSafeString(member.getHonorsAwarded()));

        // 第 11 行
        sheet.getRow(11).getCell(1).setCellValue(getSafeString(member.getCollegeOpinion()));

        // 第 13 行（初检情况，已处理空值）
        sheet.getRow(13).getCell(1).setCellValue(getSafeString(member.getInitialInspection()));


        return workbook; // 返回 Excel 对象
    }

    // 工具方法：统一处理空值
    private String getSafeString(String value) {
        return (value != null && !value.trim().isEmpty()) ? value : "-";
    }


    /**
     * 查询预征班每个学院的人数总计
     *
     * @return
     */
    public List<CollegeCountVO> getCollegeCount() {
        return retireMemberMapper.getCollegeCount();
    }

    /**
     * 查询预征班每个年级的总人数
     *
     * @return
     */
    public List<GradeCountVO> getGradeCount() {
        return retireMemberMapper.getGradeCount();
    }

    @Override
    public ClubPersionInfoVO getPersionInfo(Long studentId) {


        //查询社团信息
        PrecollectMember precollectMember = retireMemberMapper.getPrecollectMemberBystudentId(String.valueOf(studentId));

        //查询学历信息
        //TODO表中暂无，假数据代替
        List<EducationHistory> fakeEducationData = new ArrayList<>();

        // 1. 小学阶段
        EducationHistory primary = new EducationHistory();
        primary.setLevel("小学");
        primary.setSchool("第一实验小学");
        primary.setStartDate("2005-09");
        primary.setEndDate("2011-07");
        primary.setJob(Arrays.asList("班长", "少先队中队长"));
        primary.setAwards(Arrays.asList("校级三好学生", "数学竞赛一等奖"));
        // 2. 初中阶段
        EducationHistory junior = new EducationHistory();
        junior.setLevel("初中");
        junior.setSchool("实验中学");
        junior.setStartDate("2011-09");
        junior.setEndDate("2014-07");
        junior.setJob(Collections.singletonList("学生会学习部长"));
        junior.setAwards(Arrays.asList("市级优秀学生干部", "物理竞赛二等奖"));
        // 3. 高中阶段
        EducationHistory senior = new EducationHistory();
        senior.setLevel("高中");
        senior.setSchool("第一高级中学");
        senior.setStartDate("2014-09");
        senior.setEndDate("2017-07");
        senior.setJob(Arrays.asList("班长", "校篮球队队长"));
        senior.setAwards(Arrays.asList("省级三好学生", "全国作文大赛金奖"));
        // 4. 大学阶段
        EducationHistory university = new EducationHistory();
        university.setLevel("大学");
        university.setSchool("贵州财经大学");
        university.setStartDate("2017-09");
        university.setEndDate("2024-07");
        university.setJob(Arrays.asList("学生会主席", "辩论社社长"));
        university.setAwards(Arrays.asList("国家奖学金", "全国大学生创业大赛金奖"));
        // 添加到列表
        fakeEducationData.add(primary);
        fakeEducationData.add(junior);
        fakeEducationData.add(senior);
        fakeEducationData.add(university);

        //查询体侧数据
//        List<MilitaryInterestGroup> militaryInterestGroup = retireMemberMapper.getPhysicalTestByStudentId(studentId);
        String s = retireMemberMapper.getPhysicalTestByStudentId(studentId);
        // 使用Jackson解析
        ObjectMapper objectMapper = new ObjectMapper();
        List<MilitaryInterestGroup> militaryInterestGroups = null;
        try {
            militaryInterestGroups = objectMapper.readValue(
                    s,
                    new TypeReference<List<MilitaryInterestGroup>>() {
                    }
            );
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }


        ClubPersionInfoVO clubPersionInfoVO = new ClubPersionInfoVO();
        if (precollectMember != null) {
            BeanUtils.copyProperties(precollectMember, clubPersionInfoVO);
        }
        clubPersionInfoVO.setEducationHistory(fakeEducationData);
        clubPersionInfoVO.setMilitaryInterestGroups(militaryInterestGroups);
        return clubPersionInfoVO;
    }
}


